package messages_erreur;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.jms.QueueConnectionFactory;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;

import javax.jms.Queue;
import javax.jms.QueueSender;
import javax.jms.TextMessage;

import javax.jms.JMSException;

public class JMSEnvoi {

	public static final String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.rmi.registry.RegistryContextFactory";
	public static final String QUEUE_CONNECTION_FACTORY = "JQCF";
	public static final String QUEUE = "MDB_Erreur";
	
	Context context = null;
	QueueConnectionFactory qcf;
	QueueConnection connection = null;
	QueueSession session = null;
	Queue queue = null;
	QueueSender sender = null;
	TextMessage message = null;

	public Context getInitialContext() throws NamingException {
		Properties props = new Properties();
		props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.rmi.registry.RegistryContextFactory");
		props.setProperty("java.naming.factory.url.pkgs",
				"org.jonas.naming:org.jnp.interfaces");
		props.setProperty(Context.PROVIDER_URL, "127.0.0.1:16010");
		Context context = new InitialContext(props);
		return context;
		
		
		
	}

	public void send(String messageContent) {
//		Hashtable<String, String> h = new Hashtable<String, String>();
//		h.put("java.naming.factory.initial",
//				"org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");
//		h.put("java.naming.provider.url", "rmi://localhost:1099");
//		h.put("java.naming.factory.url.pkgs", "org.objectweb.jonas.naminsg");
//		
		try {
			//Context ctx = new InitialContext(h);
			context = this.getInitialContext();
			qcf = (QueueConnectionFactory) context
					.lookup(QUEUE_CONNECTION_FACTORY);
			connection = qcf.createQueueConnection();
			// session = connection.createQueueSession(false,
			// javax.jms.Session.AUTO_ACKNOWLEDGE);
			session = connection.createQueueSession(true, 0);
			queue = (Queue) context.lookup(QUEUE);
			sender = session.createSender(queue);
			message = session.createTextMessage();
			message.setText(messageContent);
			sender.send(queue, message);
			context.close();
			session.close();
			connection.close();

			// session.commit();
		} catch (NamingException ne) {
			ne.printStackTrace();
		} catch (JMSException jms) {
			jms.printStackTrace();
		} finally {
			try {
				if (context != null)
					context.close();
				if (connection != null)
					connection.close();
			} catch (Exception e) {
			}
		}
	}

}

